/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tarena.lbs.attach.controller;

import com.tarena.lbs.attach.config.MinioConfig;
import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.attach.service.AttachService;
import com.tarena.lbs.base.protocol.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Locale;
import java.util.UUID;

//@Api(value = "attach", tags = "附件中心管理")
@Slf4j
@Validated
@RestController
@RequestMapping("attach")
@Tag(name = "附件服务", description = "附件中心管理")
public class AttachController {
    @Autowired
    private AttachService attachService;

    @Autowired
    private MinioConfig minioConfig;

//    @Value("${image_path}")
//    private String imagePath;


    @PostMapping("upload")
    //@ApiOperation(value = "上传附件")
    @Operation(summary = "上传附件")
    public Result<FileVO> uploadAttachInfo(@RequestPart("file") MultipartFile file) {
//        获取存储服务器地址
        String urlPath = minioConfig.getEndpoint();
//        用uuid给图片改名
        String fileUuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(Locale.ROOT);
//        图片存储在数据库的id
        Integer fileId;

        try {
            fileId = attachService.upload(file, fileUuid);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        图片完整路径
        urlPath = "%s/%s/%s".formatted(urlPath, minioConfig.getBucketName(), fileUuid);

        FileVO fileVO = new FileVO();
        fileVO.setUrl(urlPath);
        fileVO.setFileUuid(fileUuid);
        fileVO.setId(fileId);

        return new Result<>(fileVO);
    }
}